package com.ddyx.service.impl;

import java.util.Date;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ddyx.common.util.ImageIOUtil;
import com.ddyx.model.DeviceEventData;
import com.ddyx.model.FaceImageInfo;
import com.ddyx.service.IDeviceEventDataParser;

/**
 * 赛兰设备事件解析器
 * 
 * @author zhongchzh
 *
 */
public class CylanDeviceEventDataParser implements IDeviceEventDataParser {

	private static final Logger logger = LoggerFactory.getLogger(CylanDeviceEventDataParser.class);
	
	@Override
	public DeviceEventData parse(JSONObject eventJson) {
		try {
			if(eventJson.containsKey("time") && eventJson.containsKey("cid")) {
				DeviceEventData result = new DeviceEventData();
				result.setReceivedTime(new Date());
				long time = eventJson.getLong("time");
				String cid = eventJson.getString("cid");
				result.setCapturedTime(new Date(time * 1000));
				result.setDeviceNo(cid);
				if(eventJson.containsKey("image_url") && eventJson.containsKey("persons")) {
					String image_url = eventJson.getString("image_url");
					result.setOriginalImageUrl(image_url);
					result.setOriginalImageData(ImageIOUtil.getImageBinary(image_url));
					JSONArray personsJson = eventJson.getJSONArray("persons");
					for(int i=0;i<personsJson.size();i++) {
						FaceImageInfo faceImageInfo = new FaceImageInfo();
						JSONObject json = personsJson.getJSONObject(i);
						String face_url = json.getString("face_url");
						faceImageInfo.setFaceImageUrl(face_url);
						faceImageInfo.setFaceImageData(ImageIOUtil.getImageBinary(face_url));
						result.getFaceImages().add(faceImageInfo);
					}
				} else if(eventJson.containsKey("image") && eventJson.containsKey("faces")) {
					result.setOriginalImageData(Base64.decodeBase64(eventJson.getString("image")));
					JSONArray facesJson = eventJson.getJSONArray("faces");
					for(int i=0;i<facesJson.size();i++) {
						FaceImageInfo faceImageInfo = new FaceImageInfo(); 
						faceImageInfo.setFaceImageData(Base64.decodeBase64(facesJson.get(i).toString()));
						result.getFaceImages().add(faceImageInfo);
					}
				}
				return result;
			}
		} catch(Exception err) {
			logger.error("解析赛兰设备事件数据错误。错误原因：", err);
		}
		return null;
	}

}
